package com.atguigu.gulimall.member.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExsitException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.service.MemberService;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 会员注册
     *
     * @param vo
     */
    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity entity = new MemberEntity();
        //设置会员等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());
        //检查用户名和手机号是否唯一
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());
        //赋值
        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        //密码加密 ,spring自带的加密器 BCryptPasswordEncoder.encode
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(password);
        entity.setNickname(vo.getUserName());

        //插入数据
        baseMapper.insert(entity);
    }

    /**
     * 检查邮箱是否存在
     *
     * @param phone
     * @return
     */
    @Override
    public void checkPhoneUnique(String phone) throws PhoneExsitException {
        Integer mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExsitException();
        }
    }

    /**
     * 检查用户名是否存在
     *
     * @param userName
     * @return
     */
    @Override
    public void checkUserNameUnique(String userName) throws UsernameExistException {
        Integer integer = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (integer > 0) {
            throw new UsernameExistException();
        }
    }

    /**
     * 会员登录
     *
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVo vo) {
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", vo.getLoginacct()).or().eq("mobile", vo.getLoginacct()));
        if (entity != null) {
            //spring 解密器：BCryptPasswordEncoder.matches
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(vo.getPassword(), entity.getPassword());
            if (matches) {
                return entity;
            }
        }
        return null;
    }

    /**
     * 会员社交登录
     *
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(SocialUserVo vo) {
        //登录和注册合并逻辑
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", vo.getUid()));
        MemberEntity memberEntity = new MemberEntity();
        if (entity != null) {
            //用户已注册
            memberEntity.setId(entity.getId());
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            baseMapper.updateById(memberEntity);

            memberEntity = entity;
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
        } else {
            try {
                //注册用户,通过uuid 获取社交用户信息
                Map<String, Object> map = new HashMap<>();
                map.put("access_token", vo.getAccess_token());
                map.put("uid", vo.getUid());
                String msg = HttpUtil.get("https://api.weibo.com/2/users/show.json", map);
                if (!StringUtils.isEmpty(msg) && !msg.contains("error_code")) {
                    JSONObject object = JSON.parseObject(msg);
                    String name = object.getString("name");
                    String gender = object.getString("gender");
                    String header = object.getString("profile_image_url");
                    memberEntity.setNickname(name);
                    memberEntity.setGender("m".equalsIgnoreCase(gender) ? 1 : 0);
                    memberEntity.setHeader(header);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            memberEntity.setSocialUid(vo.getUid());
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            baseMapper.insert(memberEntity);
        }
        return memberEntity;
    }
}
